package top.wettis.chat.pojo.VO;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import top.wettis.chat.constant.ResultCode;
import top.wettis.chat.constant.ResultType;

import java.io.Serializable;

@Getter
@Setter
public class Result<T> implements Serializable {

    private Integer code;
    private String msg;
    private T data;
    
    public Result(){}

    public Result(String msg){
        this.msg = msg;
    }

    public Result(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
        this.data = null;
    }

    public Result(Integer code,String msg, T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Result(ResultCode resultCode, T data){
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
        this.data = data;
    }

    public static Result<Object> customInfo(Integer code,String message,Object data) {
        return new Result<>(code,message,data);
    }

    public static Result<Object> successInfo(ResultType resultType, Object data) {
        return switch (resultType) {
            case SAVE -> new Result<>(ResultCode.SAVE_OK,data);
            case DELETE -> new Result<>(ResultCode.DELETE_OK,data);
            case GET -> new Result<>(ResultCode.GET_OK,data);
            case UPDATE -> new Result<>(ResultCode.UPDATE_OK,data);
            case LOGIN -> new Result<>(ResultCode.LOGIN_OK,data);
            case REGISTER -> new Result<>(ResultCode.REGISTER_OK,data);
        };
    }

    public static Result<Object> failInfo(ResultType resultType, Object data) {
        return switch (resultType) {
            case SAVE -> new Result<>(ResultCode.SAVE_ERR);
            case DELETE -> new Result<>(ResultCode.DELETE_ERR);
            case GET -> new Result<>(ResultCode.GET_ERR);
            case UPDATE -> new Result<>(ResultCode.UPDATE_ERR);
            case LOGIN -> new Result<>(ResultCode.LOGIN_ERR,data);
            case REGISTER -> new Result<>(ResultCode.REGISTER_ERR,data);
        };
    }

    // 包装 错误处理的结果

    public static Result<Exception> errorMsg(String msg) {
        return new Result<>(500, msg, null);
    }
    public static Result<Exception> customError(Integer code,String msg) {
        return new Result<>(code, msg, null);
    }


    //辅助函数

    public String toJSON(){
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("返回信息转换JSON异常");
        }
    }
}
